package com.example.dafafastlib.utils;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;


import com.example.dafafastlib.R;

import java.util.ArrayList;
import java.util.List;

import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;

/**
 * Created by wang_dafa on 2018/2/5.
 */
public class LocationUtil {
    private Context mContext;
    private static LocationUtil mInstance;
    private PopupWindow popupWindow;

    private LocationUtil(Context context) {
        this.mContext = context;
    }

    public static LocationUtil getmInstance(Context context) {
        if (null == mInstance) {
            mInstance = new LocationUtil(context);
        }
        return mInstance;
    }

    public Double[] getlocation() {
        Double[] locations = null;
        if (checkPermission()) {
            LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  //从gps获取经纬度
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                    locations = new Double[2];
                    locations[0] = location.getLatitude();
                    locations[1] = location.getLongitude();
                } else {//当GPS信号弱没获取到位置的时候又从网络获取
                    locations = getLngAndLatWithNetwork();
                }
            } else {    //从网络获取经纬度
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location != null) {
                    locations = new Double[2];
                    locations[0] = location.getLatitude();
                    locations[1] = location.getLongitude();
                }
            }
            return locations;
        } else {
            return null;
        }
    }

    private boolean checkPermission() {
        final boolean[] checkResult = new boolean[1];
        List<PermissionItem> permissionItems = new ArrayList<>();
        permissionItems.add(new PermissionItem(Manifest.permission.ACCESS_FINE_LOCATION));
        permissionItems.add(new PermissionItem(Manifest.permission.ACCESS_COARSE_LOCATION));
        HiPermission.create(mContext)
                .checkSinglePermission(Manifest.permission.ACCESS_FINE_LOCATION, new PermissionCallback() {
                    @Override
                    public void onClose() {
                        checkResult[0] = false;
                    }

                    @Override
                    public void onFinish() {
                        checkResult[0] = true;
                    }

                    @Override
                    public void onDeny(String permission, int position) {
                        checkResult[0] = false;
                    }

                    @Override
                    public void onGuarantee(String permission, int position) {
                        checkResult[0] = true;
                    }
                });
        return checkResult[0];
    }

    //从网络获取经纬度
    private Double[] getLngAndLatWithNetwork() {
        Double[] locations  = null;
        if (checkPermission()) {
            LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                locations = new Double[2];
                locations[0] = location.getLatitude();
                locations[1] = location.getLongitude();
            }
        }
        return locations;
    }


    private LocationListener locationListener = new LocationListener() {

        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {

        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {

        }

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
        }
    };
    public void startNavigation(int mapType,String location){
        //开始导航---mapType:0-高德 1-腾讯 2-百度
        switch (mapType){
            case 0:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_DEFAULT);

                //将功能Scheme以URI的方式传入data
                Uri uri = Uri.parse("androidamap://keywordNavi?sourceApplication=softname&keyword="+location+"&style=2");
                intent.setData(uri);
                //启动该页面即可
                mContext.startActivity(intent);
                break;
            case 1:

                break;
            case 2:
                Intent i1 = new Intent();
                i1.setData(Uri.parse("baidumap://map/direction?region=beijing&origin=我的位置&destination="+location+"&mode=walking"));
                mContext.startActivity(i1);
                break;
        }
    }
    public void showPopUpWindow(View rootVeiw,String location){
        View view = View.inflate(mContext, R.layout.dialog_selectmap,null);
        TextView mGaoDe = (TextView) view.findViewById(R.id.map_gaode);
        TextView mBaiDu = (TextView) view.findViewById(R.id.map_baidu);
        TextView mCancle = (TextView) view.findViewById(R.id.map_cancle);
        if (null == popupWindow) {
            popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        }
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        mGaoDe.setOnClickListener(v -> {
            if (PackageUtils.isApkIntalled(mContext, "com.autonavi.minimap")) {
                LocationUtil.getmInstance(mContext).startNavigation(0, location);
                popupWindow.dismiss();
            } else {
                ToastUtil.showShort(mContext, "当前手机未安装高德地图");
            }
        });
        mBaiDu.setOnClickListener(v -> {
            if (PackageUtils.isApkIntalled(mContext, "com.baidu.BaiduMap")) {
                LocationUtil.getmInstance(mContext).startNavigation(2, location);
                popupWindow.dismiss();
            } else {
                ToastUtil.showShort(mContext, "当前手机未安装百度地图");
            }
        });
        mCancle.setOnClickListener(v -> popupWindow.dismiss());
        popupWindow.showAtLocation(rootVeiw, Gravity.BOTTOM,0,0);
        popupWindow.setAnimationStyle(R.style.MyWidget_AnimationDropDownUp);
    }
}
